package com.example.springsecurity.common.config;

import com.alibaba.fastjson2.annotation.JSONField;
import com.example.springsecurity.entity.SystemUser;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：Security安全认证框架默认用户详情接口实现类
 * @Author： fengcheng
 * @Date： 2024/12/19 09:36
 */
@Data
@NoArgsConstructor
public class SystemUserLoginDetail implements UserDetails {

    private SystemUser systemUser;

    private List<String> permissions;

    @JSONField(serialize = false) // 【authorities】字段序列化时忽略
    private List<SimpleGrantedAuthority> authorities;

    @JSONField(serialize = false) // 【roles】字段序列化时忽略
    private List<String> roles;

    public SystemUserLoginDetail(SystemUser systemUser, List<String> permissions, List<String> roles) {
        this.systemUser = systemUser;
        this.permissions = permissions;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        if (!CollectionUtils.isEmpty(authorities)) return authorities;
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return systemUser.getPassword();
    }

    @Override
    public String getUsername() {
        return systemUser.getUsername();
    }

    public String getMobile() {
        return systemUser.getMobile();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
